﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace Ehai.Web.Framework.Rules
{
    class InsertOrUpdateRuleHandle : IMsgRuleHandle
    {
        #region IMsgRuleHandle 成员

#if DEBUG

        private int _execStatus = 0;
        public int ExecStatus
        {
            get { return _execStatus; }
        }
#endif
        public const string Name = "insertorupdate"; 

        private static char specChar = HttpUtility.UrlDecode("%16")[0];

        private static string replaceRevA(Match m)
        {
            return m.Value.Replace(',', specChar);
        }
        /// <summary>
        /// 传入一个字符串数组，根据数组的内容执行对数据库的操作。
        /// </summary>
        /// <param name="p">传入的字符串数组</param>
        /// <param name="ci">ContextInfo对象</param>
        /// <exception cref="Ehai.Web.Framework.WebException">
        /// 如果传入的字符串无法组成正确的SQL语句，则抛出Ehai.Web.Framework.WebException异常
        /// </exception>
        /// <returns>返回一个二维数组，两个维度均为1。第一行第一列的字符串就表示操作是否成功。</returns>
        public string[][] Execute(string[] p, ContextInfo ci)
        {
            if (p.Length < 4)
            {
#if DEBUG
                // 操作成功,状态值
                _execStatus = -2;
#endif
                return null;
            }
            for (int n = 0; n < 4; ++n)
            {
                if (String.IsNullOrEmpty(p[n]))
                {
#if DEBUG
                    _execStatus = n+1;
#endif
                    return null;
                }
            }
            string p4 = (p.Length < 5) ? String.Empty : p[4].Trim();
            string p5 = (p.Length < 6) ? String.Empty : p[5].Trim();
            string p6 = (p.Length < 7) ? String.Empty : p[6].Trim();
            string[][] result = { new string[1] { String.Empty } };
            try
            {
                int suc = -1;
                string sql = String.Empty, Logsql = String.Empty;
                ApplicationDB acsSql = new ApplicationDB(sql, ci, p6);
                if (p4.Trim() == String.Empty)//无关键字
                {
                    acsSql.Sql = "insert into " + p[1] + " (" + p[2] + ") values (" + p[3] + ")";
                    suc = acsSql.ExecuteNonQuery();
                }
                else//有关键字
                {
                    if (p5.Trim() == String.Empty) throw new Exception("关键字段未传值。");
                    string strWhere = String.Empty;
                    if (p5.IndexOf("in ") > -1) strWhere = p4 + " " + p5;
                    else
                    {
                        string[] key = p4.Split(','), keyValue = p5.Split(',');
                        if (key.Length == keyValue.Length)
                        {
                            for (int i = 0; i < key.Length; i++)
                            {
                                strWhere += key[i] + "=" + keyValue[i] + " and ";
                            }
                        }
                        strWhere = strWhere.Remove(strWhere.Length - 4);
                    }
                    acsSql.Sql = "select count(1) from " + p[1] + " where " + strWhere;//p[5] + "=" + p[6];
                    int m = Convert.ToInt32(acsSql.ExecuteScalar());
                    if (m < 1)//没有此记录则插入
                    {
                        acsSql.Sql = "insert into " + p[1] + "(" + p[2] + ") values(" + p[3] + ")";
                        suc = acsSql.ExecuteNonQuery();
                    }
                    else//有此记录则更新
                    {
                        string expression = String.Empty;
                        string[] cols = { p[2] }, values = { p[3] };
                        if (p[2].Split(',').Length > 1)
                        {
                            cols = p[2].Split(',');
                            p[3] = Regex.Replace(p[3], "(([\']).*?\\2)", new MatchEvaluator(replaceRevA));
                            values = p[3].Split(',');
                        }
                        if (cols.Length == values.Length)
                        {
                            for (int i = 0; i < cols.Length; i++)
                            {
                                expression += cols[i] + "=" + values[i].Replace(specChar, ',') + ",";
                            }
                            expression = expression.Remove(expression.Length - 1);
                            acsSql.Sql = "update " + p[1] + " set " + expression + " where " + strWhere;//p[5] + "=" + p[6];
                            suc = acsSql.ExecuteNonQuery();
                        }
                    }
                }
                if (suc > -1)
                {
                    HttpBrowserCapabilities br = ci.Request.Browser;
                    Logsql = "insert into log(msg,username,browserName,browserVersion,browserPlatform,IP,operationTime) values('" +
                        acsSql.Sql.Replace("'", "\\''").Replace("\"", "\\\"") + "','" +
                        "wangguanyu"/*ci.Session["username"]*/ + "','" + br.Browser + "','" + br.Version + "','" + br.Platform + "','" +
                        ci.Request.UserHostAddress + "','" + System.DateTime.Now + "')";
                    acsSql.Sql = Logsql;
                    acsSql.ConString = ci.GetConnectionString("id2");
                    acsSql.ExecuteNonQuery();
                    result[0][0] = "success";
#if DEBUG
                    // 操作成功,状态值
                    _execStatus = 0;
#endif
                    return result;
                }
                else
                {
                    result[0][0] = HttpContext.Current.Server.HtmlEncode("error");
                    return result;
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                // 操作成功,状态值
                _execStatus = -1;
#endif
                throw new Ehai.Web.Framework.WebException("Ehai.Web.InsertOrUpdate", "数据库操作异常！", ex);
            }
        }

        public string GetHelpInfo()
        {
            return "传入一个字符串数组，根据数组的内容执行对数据库的操作。";
        }

        public string GetHelpDetail()
        {
            return "传入操作类型、表名、列名、列值、关键字、关键字的值和数据库连接字符串</br>" + "例如：{update, wang, id,name, 1007,\'Lowry\', id, 1002, id1}</br>"+"返回：操作的最终结果，若成功，返回success；若失败，返回error；如果是抛出了异常，异常的具体信息也返回来";
        }

        public string[] GetParametersInfo()
        {
            string[] info = new string[7];
            info[0] = "(必选)处理类型InsertOrUpdate(不能为空或空字符串)";
            info[1] = "(必选)表名(不能为空或空字符串)</br>";
            info[2] = "(必选)列名(不能为空或空字符串)，格式为：\"col1,col2,col3......\"";
            info[3] = "(必选)值(不能为空或空字符串)，格式为：\"val1,val2,val3......\"";
            info[4] = "(可选)关键字(可以为空或空字符串)，格式为：\"key1,key2,key3......\"";
            info[5] = "(可选，但如果4不为空，5也不能为空)关键字的值(不能为空或空字符串)，格式为：\"keyvalue1,keyvalue2,keyvalue3......\"";
            info[6] = "(可选)数据库连接字符串的id(可以为空或空字符串)";
            return info;
        }

        #endregion
    }
}
